import type { Router } from "vue-router"
import { usePermissionStore } from "@/pinia/stores/permission"
import { isWhiteList } from "@/router/whitelist"
import { setRouteChange } from "@@/composables/useRouteListener"
import { useTitle } from "@@/composables/useTitle"
import { getToken } from "@@/utils/cache/cookies"
import NProgress from "nprogress"

NProgress.configure({ showSpinner: false })

const { setTitle } = useTitle()
const LOGIN_PATH = "/login"

export function registerNavigationGuard(router: Router) {
  router.beforeEach((to) => {
    NProgress.start()

    const token = getToken()
    if (!token) {
      if (isWhiteList(to)) return true
      return "/login"
    }

    const permissionStore = usePermissionStore()
    if (permissionStore.routes.length === 0) {
      permissionStore.setAllRoutes()
    }

    return true
  })

  router.afterEach((to) => {
    setRouteChange(to)
    setTitle(to.meta.title)
    NProgress.done()
  })
}
